package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.dialog.ImageSelectDialog;
import com.jiaoyou.baojian.entity.UploadEntity;
import com.jiaoyou.baojian.entity.UserInfo;
import com.jiaoyou.baojian.entity.response.LoginResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.utils.Utils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class CreateUserInfoActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.header)
    ImageView header;
    @BindView(R.id.nickname)
    EditText nickname;
    @BindView(R.id.gender)
    TextView gender;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.info)
    EditText info;
    @BindView(R.id.enter)
    Button enter;

    private OptionsPickerView genderPickerView;
    private TimePickerView birthdayPickerView;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private CropOptions cropOptions;
    private Uri outputUri;
    private String userHeaderUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

        ButterKnife.bind(this);
        setTitle("填写个人信息");

        cropOptions = getCropOptions();
        configTakePhotoOption();
        configCompress();
    }

    @Override
    public void initData() {
        final List<String> genderList = new ArrayList<>();
        genderPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                gender.setText(genderList.get(options1));
            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("性别选择")
                .setSubCalSize(18)
                .setContentTextSize(18)
                .setCyclic(false, false, false)
                .setOutSideCancelable(true)
                .isDialog(false)
                .build();
        genderList.add("男");
        genderList.add("女");
        genderPickerView.setPicker(genderList);

        birthdayPickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                birthday.setText(format.format(date));
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                .build();
        birthdayPickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    @Override
    public int getContentView() {
        return R.layout.activity_create_user_info;
    }

    @OnClick({R.id.header, R.id.gender, R.id.birthday, R.id.enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.header:
                showImageSelectDialog(new ImageSelectDialog.OnImageSelectListener() {
                    @Override
                    public void onSelectCamera() {
                        generalOutputUri();
                        getTakePhoto().onPickFromCaptureWithCrop(outputUri, cropOptions);
                    }

                    @Override
                    public void onSelectGallery() {
                        generalOutputUri();
                        getTakePhoto().onPickFromGalleryWithCrop(outputUri, cropOptions);
                    }
                });
                break;
            case R.id.gender:
                Utils.hideKeyboard(gender, this);
                genderPickerView.show();
                break;
            case R.id.birthday:
                Utils.hideKeyboard(birthday, this);
                birthdayPickerView.show();
                break;
            case R.id.enter:
                if(TextUtils.isEmpty(userHeaderUrl) || TextUtils.isEmpty(nickname.getEditableText().toString())
                        || TextUtils.isEmpty(gender.getText())
                        || TextUtils.isEmpty(birthday.getText())
                        || TextUtils.isEmpty(info.getEditableText().toString())){
                    toast("数据不能为空");
                    return;
                }
                waiting("提交数据...");
                String sex = null;
                if(gender.getText().equals("男"))
                    sex = "M";
                else if(gender.getText().equals("女"))
                    sex = "F";

                Api.getInstance().modifyUserInfo(userHeaderUrl, null, nickname.getEditableText().toString(), sex, "", birthday.getText().toString(), info.getEditableText().toString(), 0, new BaofangCallback() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        stopWaiting();
                        toast("提交个人信息失败:" + t.getLocalizedMessage());
                    }

                    @Override
                    public void onSuccess(Object o) {
                        stopWaiting();
                        toast("个人信息保存成功");
                        Api.getInstance().getUserInfo(new BaofangCallback<UserInfo>(){

                            @Override
                            public void onFailure(Call<BaseResponse<UserInfo>> call, Throwable t) {

                            }

                            @Override
                            public void onSuccess(UserInfo userInfo) {
                                getLoginResponse().userInfo = userInfo;
                                getACache().put(LoginResponse.TAG, new Gson().toJson(getLoginResponse()));
                            }
                        });
                        finish();
                    }
                });
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void takeSuccess(final TResult result) {
        ///data/user/0/com.jiaoyou.baojian/cache/takephoto_cache/1494340603729.jpg
        waiting("上传图片...");
        Api.getInstance().uploadAvatarImage(new File(result.getImage().getCompressPath()), new BaofangCallback<UploadEntity>(){

            @Override
            public void onFailure(Call<BaseResponse<UploadEntity>> call, Throwable t) {
                stopWaiting();
                toast("上传失败：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(UploadEntity uploadEntity) {
                stopWaiting();
                userHeaderUrl = uploadEntity.relativePath;
                Glide.with(CreateUserInfoActivity.this).load(result.getImage().getCompressPath()).crossFade().into(header);
//                Glide.with(CreateBaofangActivity.this).load(roomCoverUrl).crossFade().into(cover);
            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void takeCancel() {
//        Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(false);
        builder.setCorrectImage(true);
        getTakePhoto().setTakePhotoOptions(builder.create());
    }
    private void configCompress(){
        CompressConfig config;
        config = new CompressConfig.Builder()
                .setMaxSize(100 * 1024)
                .setMaxPixel(200)
                .enableReserveRaw(true)
                .create();
        getTakePhoto().onEnableCompress(config, true);
    }
    private CropOptions getCropOptions(){
        CropOptions.Builder builder=new CropOptions.Builder();
        builder.setAspectX(1).setAspectY(1);
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }
    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }
    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    private void generalOutputUri(){
        configCompress();
        File file = Utils.generalTempFile(".jpg");
        outputUri = Uri.fromFile(file);
    }
}
